package com.wx.house.common.util;


import com.wx.house.common.exception.BusinessException;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Component
@RequiredArgsConstructor
public class RedisUtil {
private final StringRedisTemplate stringRedisTemplate;

public void set(String key, String value) {
	stringRedisTemplate.opsForValue().set(key, value);
}


public void set(String key, String value, Long expired, TimeUnit timeUnit) {
	stringRedisTemplate.opsForValue().set(key, value, expired, timeUnit);
}

public void delete(String key) {
	stringRedisTemplate.delete(key);
}

public String get(String key) {
	return stringRedisTemplate.opsForValue().get(key);
}

public <T> T getObj(String key, Class<T> o) {
	String json;
	try {
		json = stringRedisTemplate.opsForValue().get(key);
	} catch (Exception e) {
		throw new BusinessException("要查询的key不存在");
	}
	T t;
	try {
		t = JsonUtils.jsonToPojo(json, o);
	} catch (Exception e) {
		throw new BusinessException("json转对象失败");
	}
	return t;
}

public <T> void setJson(String key, T o) {
	stringRedisTemplate.opsForValue().set(key, Objects.requireNonNull(JsonUtils.objectToJson(o)));
}

/**
 * @Description 根据key规则获取一些key
 * @Param keys
 * @Return java.util.Set<java.lang.String>
 */
public Set<String> keys(String keys) {
	return stringRedisTemplate.keys(keys);
}

public List<String> getListByKey(String keys) {
	return Objects.requireNonNull(stringRedisTemplate.keys(keys))
			       .stream()
			       .map(this::get)
			       .collect(Collectors.toList());
}

/**
 * @Description 根据key规则获取查询结果列表
 * @Param keys
 * @Return Map<key, value>
 */
public Map<String, String> getMapByKey(String keys) {
	return Objects.requireNonNull(stringRedisTemplate.keys(keys))
			       .stream()
			       .collect(Collectors.toMap(
					       e -> e,
					       this::get,
					       (a, b) -> b));
}

public void setExpire(String key, Integer time) {
	stringRedisTemplate.expire(key, time, TimeUnit.SECONDS);
}
}
